package com.hrvsr.common.util;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

import org.apache.commons.io.IOUtils;

public class SerializationUtil {

	public static byte[] serialize(Object obj) {
		ByteArrayOutputStream byteArrOut = null;
		try {
			byteArrOut = new ByteArrayOutputStream();
			ObjectOutputStream out = new ObjectOutputStream(byteArrOut);
			out.writeObject(obj);
			out.flush();
			return byteArrOut.toByteArray();
		} catch (Exception e) {
			e.printStackTrace();
			// ignore
		} finally {
			IOUtils.closeQuietly(byteArrOut);
		}
		return null;
	}

	public static Object unSerialize(byte[] bytes) {
		ByteArrayInputStream in1 = null;
		try {
			in1 = new ByteArrayInputStream(bytes);
			ObjectInputStream in2 = new ObjectInputStream(in1);
			Object object = in2.readObject();
			return object;
		} catch (Exception e) {
			// ignore
		} finally {
			IOUtils.closeQuietly(in1);
		}
		return null;
	}

	@SuppressWarnings("unchecked")
	public static <T> T unSerialize(byte[] bytes, Class<T> T) {
		Object o = unSerialize(bytes);
		return (T) o;
	}

}
